<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="sourceName">
        <el-input
          v-model="queryParams.sourceName"
          placeholder="请输入数据源名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="sourceCode">
        <el-input
          v-model="queryParams.sourceCode"
          placeholder="请输入数据源编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="类型" prop="sourceType">
        <el-select v-model="queryParams.sourceType" placeholder="请选择数据源类型" clearable size="small">
          <el-option label="mysql" value="mysql" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable size="small">
          <el-option label="开启" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="datasourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="数据源名称" align="center" prop="sourceName" />
      <el-table-column label="数据源编码" align="center" prop="sourceCode" />
      <el-table-column label="数据源类型" align="center" prop="sourceType" />
<!--      <el-table-column label="URL" align="center" prop="url" />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="密码" align="center" prop="password" /> -->
      <!-- <el-table-column label="状态" align="center" prop="state" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据源名称" prop="sourceName">
          <el-input v-model="form.sourceName" placeholder="请输入数据源名称" />
        </el-form-item>
        <el-form-item label="数据源编码" prop="sourceCode">
          <el-input v-model="form.sourceCode" placeholder="请输入数据源编码" />
        </el-form-item>
        <el-form-item label="数据源类型" prop="sourceType">
          <el-select v-model="form.sourceType" placeholder="请选择数据源类型" @change="checkSourceType(form.sourceType)">
            <el-option label="MYSQL" value="MYSQL" />
            <el-option label="HTTP" value="HTTP" />
          </el-select>
        </el-form-item>
        <el-form-item label="URL" prop="url">
          <el-input v-model="form.url" placeholder="请输入连接地址" />
        </el-form-item>

        <el-form-item label="用户名" prop="userName" v-show="paramShow == false">
          <el-input v-model="form.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-show="paramShow == false">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item label="请求头" v-show="paramShow">
          <Vue2AceEditor
                v-model="form.headers"
                @init="editorInit"
                lang="json"
                theme='monokai'
                :options="editorOptions"
                width="100%"
                height="100"
              />
        </el-form-item>

        <el-form-item label="参数" v-show="paramShow">
          <Vue2AceEditor
                v-model="form.values"
                @init="editorInit"
                lang="json"
                theme='monokai'
                :options="editorOptions"
                width="100%"
                height="100"
              />
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option label="开启" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="testDataSource">测 试</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {
        addDatasource,
        delDatasource,
        getDatasource,
        pageDatasource,
        updateDatasource,
        testDatasource
    } from "@/api/datasource/datasource";
    import ImageUpload from '@/components/ImageUpload';
    import FileUpload from '@/components/FileUpload';
    import Editor from '@/components/Editor';

export default {
  name: "Datasource",
  components: {
    Vue2AceEditor: require('vue2-ace-editor'),
  },
  data() {
    return {
      paramShow: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据源管理表格数据
      datasourceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        sourceName: null,
        sourceCode: null,
        sourceType: null,
        url: null,
        userName: null,
        password: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      },
      // 表单参数
      form: {
        params: {
          headers: {},
          values: {}
        }
      },
      // 表单校验
      rules: {
        sourceName: [
          { required: true, message: "数据源名称不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        url: [
          { required: true, message: "url不能为空", trigger: "change" }
        ],
        sourceType: [
          { required: true, message: "数据源类型不能为空", trigger: "change" }
        ],
        // userName: [
        //   { required: true, message: "用户名不能为空", trigger: "change" }
        // ],
        // password: [
        //   { required: true, message: "密码不能为空", trigger: "change" }
        // ],
        state: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      editorOptions: {
              // 设置代码编辑器的样式
              enableBasicAutocompletion: true,
              enableSnippets: true,
              enableLiveAutocompletion: true,
              tabSize: 2,
              fontSize: 16,
              showPrintMargin: false //去除编辑器里的竖线
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据源管理列表 */
    getList() {
      this.loading = true;
      pageDatasource(this.queryParams).then(response => {
        this.datasourceList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sourceName: null,
        sourceCode: null,
        sourceType: null,
        url: null,
        userName: null,
        password: null,
        state: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据源管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDatasource(id).then(response => {
        this.form = response.data;
        this.form.state = this.form.state+'';
        this.open = true;
        this.title = "修改数据源管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            const params = {
              headers: this.form.headers,
              values: this.form.values
            }
            this.form.params = params
            updateDatasource(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDatasource(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 测试按钮 */
    testDataSource() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            const params = {
              headers: this.form.headers,
              values: this.form.values
            }
            this.form.params = params
            testDatasource(this.form).then(response => {
              this.msgSuccess(response.msg);
            });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除数据源管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDatasource(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datasource/manager/export', {
        ...this.queryParams
      }, `datasource_manager.xlsx`)
    },
    checkSourceType(value){
      if(value == 'HTTP'){
        this.paramShow = true;
      }else{
        this.paramShow = false;
      }
    },
    editorInit: function() {
          require("brace/theme/chrome");
          require("brace/theme/github");
          require("brace/theme/eclipse");
          require("brace/theme/monokai");
          require("brace/theme/textmate");
          require("brace/ext/language_tools"); //language extension prerequsite...
          require("brace/mode/yaml");
          require("brace/mode/json");
          require("brace/mode/less");
          require("brace/mode/java");
          require("brace/snippets/json");
          require("brace/snippets/java");
    }
  }
};
</script>
